<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mall:logistics:add']"
        >新增</el-button>
      </el-col>
    </el-row>

    <div class="temp-item" v-for="(item, idx) in templateList" :key="idx">
      <div class="header">
        <div class="left">
          <div class="name">{{ item.freightTemplate.name }}</div>
          <el-tag v-if="item.freightTemplate.pricingMethod == 'FREE'" type="warning" style="margin-left: 10px;">包邮</el-tag>
        </div>
        <el-button
          style="margin-left: 10px;"
          size="mini"
          type="success"
          @click="handleUpdate(item)">修改</el-button>
        <el-button
          style="margin-left: 10px;"
          size="mini"
          type="danger"
          @click="handleDeleteTemplate(item)">删除</el-button>

      </div>
      <el-table
        v-if="item.freightTemplateChildList && item.freightTemplate.pricingMethod != 'FREE'"
        :data="item.freightTemplateChildList"
        style="width: 100%"
      >
      <el-table-column
        prop="area"
        label="运送到">
      </el-table-column>
      <el-table-column
        prop="firstCompany"
        align="center"
        label="首件(重)"
        width="120">
      </el-table-column>
      <el-table-column
        prop="firstPrice"
        align="center"
        width="120"
        label="运费">
      </el-table-column>
      <el-table-column
        prop="continuedCompany"
        align="center"
        width="120"
        label="续件(重)">
      </el-table-column>
      <el-table-column
        prop="continuedPrice"
        align="center"
        width="120"
        label="运费">
      </el-table-column>
      </el-table>
    </div>

    <!-- 添加或修改运费模版 -->
    <el-dialog :title="title" :visible="open" width="100%" append-to-body>
      <el-form ref="addForm" :model="addForm" :rules="rules" label-width="80px">
        <el-form-item label="模板名称" prop="code">
          <el-input v-model="addForm.freightTemplate.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="计价方式" prop="isEnable">
          <el-radio-group v-model="addForm.freightTemplate.pricingMethod" size="small">
            <el-radio-button label="WEIGHT">按重量</el-radio-button>
            <el-radio-button label="NUM">按件数</el-radio-button>
            <el-radio-button label="FREE">包邮</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="addForm.freightTemplate.pricingMethod != 'FREE'">
          <el-table
            :data="addForm.freightTemplateChildList"
            style="width: 100%"
          >
          <el-table-column
            prop="area"
            label="运送到">
              <template slot-scope="cascaderScope">
                <el-cascader
                  v-model="cascaderScope.row.areaIdArray"
                  style="width: 90%"
                  ref="cascaderAddr"
                  collapse-tags
                  size="medium"
                  :options="dealAreaItemData(cascaderScope.$index, cascaderScope.row)"
                  :props="props"
                  @change="(value) => handleAreaChange(cascaderScope.$index, value)"></el-cascader>
              </template>
          </el-table-column>
          <el-table-column
            prop="firstCompany"
            align="center"
            label="首件(重)">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.firstCompany" controls-position="right" @change="handleChange" :min="0" :max="10" size="small"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            prop="firstPrice"
            align="center"
            label="运费">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.firstPrice"  controls-position="right" @change="handleChange" :min="0" :max="10" size="small"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            prop="continuedCompany"
            align="center"
            label="续件(重)">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.continuedCompany" controls-position="right" @change="handleChange" :min="0" :max="10" size="small"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            prop="continuedPrice"
            align="center"
            label="运费">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.continuedPrice" controls-position="right" @change="handleChange" :min="0" :max="10" size="small"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div style="flex: 1; display: flex; justify-content: start;" >
          <el-button icon="el-icon-edit" type="primary" @click="addFormItem">为指定城市设置运费模版</el-button>
        </div>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { delLogistics, getFreightTemplateList, addFreightTemplateList, delFreightTemplate, updateFreightTemplate } from "@/api/mall/seting/freightTemplate";

import { cascade } from "@/api/cms/area";

export default {
  name: "Logistics",
  dicts: ['sys_is_enable'],
  data() {
    return {
      pricingMethodMap: {
        'WEIGHT': '按重量',
        'NUM': '按件数',
        'FREE': '包邮',
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物流公司表格数据
      logisticsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单校验
      rules: {
      },
      areaoptions: [],
      props: {
        value: 'id',
        label: 'name',
        multiple: true
      },
      templateType: {},
      labelPosition: 'right',
      // 模版列表
      templateList: [],
      // 添加/ 修改弹框
      modalType: 'add',
      addForm: {
        freightTemplate: {
          // 模板名称
          name: 'test',
          // 计价方式：按件、按重量、包邮
          pricingMethod: 'WEIGHT',
        },
        freightTemplateChildList: [
          {
            area: '',
            areaId: '',
            // 首重/首件
            firstCompany: 0,
            // 运费
            firstPrice: 0,
            // 续重/续件
            continuedCompany: 0,
            // 续费
            continuedPrice: 0,
            areaIdArray: [],
          },
        ]
      },
    };
  },
  created() {
    this.fetchFreightTemplateList();
    this.fetchCascade();
  },
  methods: {
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.addForm = {
        freightTemplate: {
          // 模板名称
          name: 'test',
          // 计价方式：按件、按重量、包邮
          pricingMethod: 'WEIGHT',
        },
        freightTemplateChildList: [
          {
            area: '',
            areaId: '',
            // 首重/首件
            firstCompany: 0,
            // 运费
            firstPrice: 0,
            // 续重/续件
            continuedCompany: 0,
            // 续费
            continuedPrice: 0,
          },
        ]
      };
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.modalType = 'add';
      this.title = "添加运费模版";
    },
    /** 修改按钮操作 */
    handleUpdate(item) {
      this.reset();
      this.title = "修改运费模版";
      this.modalType = 'edit';

      const newfreightTemplateChildList = [];
      item.freightTemplateChildList.map(freightTemplateChildItem => {
        // freightTemplateChildItem.areaId 根据,分隔
        // freightTemplateChildItem.areaId.split(',')
        console.log('freightTemplateChildItem.areaId.spl', freightTemplateChildItem.areaId.split(','))
        const areaItemList = freightTemplateChildItem.areaId.split(',') || [];
        const areaIdArray = [];
        areaItemList.map(areaId => {
          const currProvince = this.areaoptions.filter(areaopt => areaopt.children?.some(obj => obj.id === areaId))[0] || {}
          areaIdArray.push([currProvince.id, areaId]);
        });

        console.log('areaIdArray', areaIdArray)
        newfreightTemplateChildList.push({
          ...freightTemplateChildItem,
          areaIdArray: [...areaIdArray],
        });
      });

      this.addForm = {
        ...item,
        freightTemplateChildList: [...newfreightTemplateChildList],
      };
      this.open = true;
    },
    /** 提交按钮 */
    submitForm() {
      console.log('addForm', this.addForm)
      this.modalType == 'add' ?
      addFreightTemplateList(this.addForm).then(res => {
        console.log('addForm---', res)
        this.open = false;
      })
      :
      updateFreightTemplate(this.addForm).then(res => {
        console.log('edidForm---', res)
        this.open = false;
      })
    },
    /** 删除按钮操作 */
    handleDelete(row, tt) {
      console.log('rowrow', row, tt)
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物流公司编号为"' + ids + '"的数据项？').then(function() {
        return delLogistics(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    fetchFreightTemplateList() {
      getFreightTemplateList().then(res => {
        console.log('resres', res)
        this.templateList = res.data || [];
      })
    },
    fetchCascade() {
      cascade(2).then(res => {
        console.log('res999', res)
        this.areaoptions = res.data;
      });
    },
    handleAreaChange(index, value) { // 表单内选中的省市县数据
      // console.log("area:" + JSON.stringify(value))
      console.log("area:", value)
      console.log("area:", index)
      // this.form.addressPathId = value.join(",");
      const nodeList = this.$refs['cascaderAddr'].getCheckedNodes();
      // const  thsAreaCode = node.pathLabels   //注意2： 获取label值
      console.log('thsAreaCode', nodeList)
      let area = '';
      nodeList.forEach((it,idx) => {
        if (0 == idx) {
          area = it.label;
        } else {
          area = area +  ',' + it.label;
        }
      });

      let areaId = '';
      value.forEach((it,idx) => {
        if (0 == idx) {
          areaId = it[1];
        } else {
          areaId = areaId +  ',' + it[1];
        }
      });
      this.addForm.freightTemplateChildList[index].areaId = areaId;
      this.addForm.freightTemplateChildList[index].area = area;

    },

    addFormItem() {
      this.addForm.freightTemplateChildList.push({
        area: '',
        areaId: '',
        // 首重/首件
        firstCompany: 0,
        // 运费
        firstPrice: 0,
        // 续重/续件
        continuedCompany: 0,
        // 续费
        continuedPrice: 0,
      });
    },
    dealAreaItemData(index, row) {
      // this.areaoptions
      // this.areaoptions
      console.log('dealAreaItemData', this.areaoptions)
      console.log('dealAreaItemData', row);
      // 遍历表单中， this.addForm.freightTemplateChildList 中的area有值， 则已选中， 非本index时 禁止选择
      let temp = '';
      this.addForm.freightTemplateChildList.forEach((el, idx) => {
        if (idx != index && el.areaId) {
          // 禁用
          temp = temp + ',' + el.areaId;
        }
      });
      console.log('temp', temp);
      // this.areaoptions 的条目的childer过滤 设置 disabled 为true
      const curData = [...this.areaoptions];
      curData.forEach(item => {
        item.children && item.children?.forEach((it, idx) => {
          if (temp.split(',').includes(it.id)) {
            // 已经有
            item.children[idx] = {
              ...item.children[idx],
              disabled: true,
            };
          }
        });
      });

      curData.forEach((item, idx) => {
        // 每个子对象是否都包含disabled属性且是true
        if (item.children && item.children?.every(obj => obj.hasOwnProperty("disabled") && obj.disabled)){
          curData[idx] = {
            ...item,
            disabled: true,
          };
        }
      });

      console.log('curData', curData)
      return curData;
    },
    handleDeleteTemplate(item) {
      console.log(item)
      delFreightTemplate(item.freightTemplate.id).then(res => {
        console.log('99999', res)
        this.fetchFreightTemplateList();
      });
    },
  }
};
</script>
<style scoped lang="scss">

.temp-item {
  margin-top: 20px;
  border: 1px solid #dfe6ec;
  border-bottom: none;
}
.header {
  display: flex;
  flex-direction: row;
  height: 44px;
  align-items: center;
  padding: 0 10px;
  background-color: #f8f8f9;
  border-bottom: 1px solid #dfe6ec;

  .left {
    flex: 1;
    display: flex;
    flex-direction: row;
    align-items: center;
  }
}

.dialog-footer {
  display: flex;
  flex-direction: row;
}
</style>
